# -*- coding: utf-8 -*-
# @Time    : 2019/10/24 15:05
# @Author  : LiHaowen
# @Email   : lihaowen2017@163.com
# @File    : thread_condition使用原因_lock缺陷.py
from threading import Condition
import threading
import time

# Condition : 条件变量，用于复杂的线程间同步


lock = threading.Lock()


class XiaoAi(threading.Thread):
    def __init__(self, lock):
        self.lock = lock
        super(XiaoAi, self).__init__(name="小爱")

    def run(self) -> None:
        self.lock.acquire()
        print(f"{self.name}: 在")
        self.lock.release()
        # time.sleep(1)
        self.lock.acquire()
        print(f"{self.name}: 没吃")
        self.lock.release()


class TianMao(threading.Thread):
    def __init__(self, lock):
        self.lock = lock
        super(TianMao, self).__init__(name="天猫精灵")

    def run(self) -> None:
        self.lock.acquire()
        print(f"{self.name}: 小爱同学")
        self.lock.release()
        # time.sleep(1)
        self.lock.acquire()
        print(f"{self.name}: 吃了吗")
        self.lock.release()


if __name__ == '__main__':
    xiaoai = XiaoAi(lock)
    tianmao = TianMao(lock)

    tianmao.start()
    xiaoai.start()
"""
天猫精灵: 小爱同学
天猫精灵: 吃了吗
小爱: 在
小爱: 没吃
"""
# 失败原因：gil根据时间片切换由于线程中锁对象内部的执行逻辑时间较少，
# gil未进行线程切换时，锁已经释放并执行下一次线程内部获得锁操作
# 可发现加入time.sleep该问题得已解决，应征该问题出现原因。
